import { createStore } from 'redux'

// 全局数据的初始状态
const initialModel = {
  users: [
    {
      id: 'UID000001',
      name: '张三',
    },
    {
      id: 'UID000002',
      name: '李四',
    },
  ],

  products: [],

  something: 'yeah',
}

export default createStore((model = initialModel, action) => {
  const { users } = model

  switch (action.type) {
    case 'create_user':
      const { user } = action.payload

      user.id =
        'UID' + String(Math.floor(Math.random() * 1000000)).padStart(6, '0')

      return {
        users: users.concat([user]),
      }

    case 'delete_user':
      const { id: targetId } = action.payload

      return {
        users: users.filter(user => user.id !== targetId),
      }

    case 'update_user':
      const { user: newUser } = action.payload

      return {
        users: users.map(user => (user.id === newUser.id ? newUser : user)),
      }

    default:
      return model
  }
})
